package com.zjlanyun.erp.interior;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;

import com.AndroidVersions;
import com.aihook.alertview.library.AlertView;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.fntech.m10a.gpio.M10A_GPIO;
import com.zjlanyun.erp.Common;
import com.zjlanyun.erp.ConnectSetup;
import com.zjlanyun.erp.Data;
import com.zjlanyun.erp.MainApplication;
import com.zjlanyun.erp.R;
import com.zjlanyun.erp.config.AppConfig;
import com.zjlanyun.erp.interior.production.ActivateCard;
import com.zjlanyun.erp.interior.production.ChangeProduct;
import com.zjlanyun.erp.interior.production.ChangeType;
import com.zjlanyun.erp.interior.production.LingliaoBind;
import com.zjlanyun.erp.interior.production.Loading;
import com.zjlanyun.erp.interior.production.LoadingCheck;
import com.zjlanyun.erp.interior.production.MaterialCheck;
import com.zjlanyun.erp.interior.production.Merge;
import com.zjlanyun.erp.interior.production.PutInStorage;
import com.zjlanyun.erp.interior.production.Rewind;
import com.zjlanyun.erp.interior.production.Split;
import com.zjlanyun.erp.interior.production.StateView;
import com.zjlanyun.erp.interior.production.Unloading;
import com.zjlanyun.erp.interior.warehouse.BeginData;
import com.zjlanyun.erp.interior.warehouse.Inventory;
import com.zjlanyun.erp.interior.warehouse.SaleOut;
import com.zjlanyun.erp.interior.warehouse.SaleOutBill;
import com.zjlanyun.erp.rfid.m10.u8.activity.RFIDSetting;
import com.zjlanyun.erp.rfid.m10.u8.reader.server.ReaderBase;
import com.zjlanyun.erp.rfid.m10.u8.reader.server.ReaderHelper;
import com.zjlanyun.erp.rfid.m10.u8.utils.M10_GPIO;
import com.zjlanyun.erp.utils.StatusBarUtil;
import com.zjlanyun.erp.utils.Toastor;
import com.zjlanyun.erp.utils.UpdateManager;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

import android_serialport_api.SerialPort;

/**
 * @author: shun
 * @date: 2016-12-27 20:31
 * @Desc:
 */

public class InteriorMainGrid extends Activity {

    private Context mContext = this;
    private LinearLayout ll_menu;
    private String[] menuTitles = {"连接设置", "解除绑定", "检查更新", "注销"};
    private int[] menuImages = {R.drawable.icon_connect_setup, R.drawable.ic_lock_open_black_24dp, R.drawable.ic_cached_black_24dp, R.drawable.icon_logout};
    private Activity mActivity = this;
    private GridView gridView;
    private SimpleAdapter mSimpleAdapter;
    private ArrayList<HashMap<String, Object>> mList;
    private int[] listIcon; //功能图标
    private String[] listTitle; //功能标题
    private Class[] mClass; //功能页面类
    private HashMap<Integer, Integer> moduleNum; //模块编号
    private ArrayList<Integer> moduleNumList; //模块编号list

    private SerialPort mSerialPort = null;
    public ReaderHelper mReaderHelper;
    public ReaderBase mReader;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.interior_main_grid);
        ((MainApplication) getApplication()).addActivity(this);
        //设置状态栏颜色
        if (StatusBarUtil.StatusBarLightMode(this) > 0) {
            StatusBarUtil.transparencyBar(this);
            findViewById(R.id.ll_status_bar).setVisibility(View.VISIBLE);
        }
        initView();
        initRFID();
    }

    @Override
    protected void onResume() {
        if (mReader != null) {
            if (!mReader.IsAlive())
                mReader.StartWait();
        }
        super.onResume();
    }

    // 初始化view
    private void initView() {
        ll_menu = (LinearLayout) findViewById(R.id.ll_menu);
        gridView = (GridView) findViewById(R.id.gridview);

        moduleNumList = new ArrayList<>();
        moduleNumList.add(71123);
        moduleNumList.add(71101);
        moduleNumList.add(71102);
        moduleNumList.add(71103);
        moduleNumList.add(71104);
        moduleNumList.add(71105);
        moduleNumList.add(71106);
        moduleNumList.add(71119);
        moduleNumList.add(71107);
        moduleNumList.add(71108);
        moduleNumList.add(71121);
        moduleNumList.add(71109);
        moduleNumList.add(71110);
        moduleNumList.add(71111);
        moduleNumList.add(71112);
        moduleNumList.add(71120);
        moduleNumList.add(71113);
        moduleNumList.add(71114);
        moduleNumList.add(71115);
        moduleNumList.add(71116);
        moduleNumList.add(71117);
        moduleNumList.add(71118);
        moduleNumList.add(71122);


        final int[] allListIcon = {R.drawable.lingliao, R.drawable.shangjia, R.drawable.shangjijiance, R.drawable.huanban, R.drawable.chaijuan, R.drawable.hebing, R.drawable.xiajia, R.drawable.fujuan, R.drawable.fujuanhebing, R.drawable.fujuanchaifen, R.drawable.gaiproduct, R.drawable.lailiaojianyan, R.drawable.gai, R.drawable.pandian, R.drawable.ruku, R.drawable.bind, R.drawable.xiaoshouchuku, R.drawable.chengpinruku, R.drawable.xiaoshoutuihuo, R.drawable.qichu, R.drawable.qingka, R.drawable.kaika, R.drawable.query};
        final String[] allListTitle = {"领料备货", "上机", "在线检验", "换班", "拆卷", "并卷", "下机", "复卷", "复卷合并", "复卷拆分", "改产品", "来料检验", "改状态", "盘点", "原料入库", "销售出库绑定", "销售出库", "成品入库", "销售退货", "期初盘点", "清卡", "开卡", "状态查看"};
        Class[] allmClass = {LingliaoBind.class, Loading.class, LoadingCheck.class, Unloading.class, Split.class, Merge.class, Unloading.class, Rewind.class, Rewind.class, Rewind.class, ChangeProduct.class,MaterialCheck.class, ChangeType.class, Inventory.class, PutInStorage.class, SaleOutBill.class, SaleOut.class, PutInStorage.class, PutInStorage.class, BeginData.class, ActivateCard.class, ActivateCard.class, StateView.class};

        //判断演示的显示所有功能
        if (AppConfig.getInstance().getBoolean("isDemo", true)) {
            listIcon = allListIcon;
            listTitle = allListTitle;
            mClass = allmClass;
        } else {
            //显示拥有的模块
            String modules = AppConfig.getInstance().getString("moduleNum", "");
            if (!modules.equals("")) {
                int index;
                JSONArray moduleArray = JSON.parseArray(modules);
                listIcon = new int[moduleArray.size()];
                listTitle = new String[moduleArray.size()];
                mClass = new Class[moduleArray.size()];

                int j = 0;
                for (int i = 0; i < moduleNumList.size(); i++) {
                    if (moduleArray.contains(moduleNumList.get(i))) {
                        listIcon[j] = allListIcon[i];
                        listTitle[j] = allListTitle[i];
                        mClass[j] = allmClass[i];
                        j++;
                    }
                }
            }
        }

        mList = new ArrayList<>();
        for (int i = 0; i < listTitle.length; i++) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("title", listTitle[i]);
            map.put("icon", listIcon[i]);
            mList.add(map);
        }
        mSimpleAdapter = new SimpleAdapter(mContext, mList, R.layout.grid_item, new String[]{"icon", "title"}, new int[]{R.id.iv_icon, R.id.tv_title});
        gridView.setAdapter(mSimpleAdapter);

        // 功能
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundle = new Bundle();
                bundle.putString("title", listTitle[position]);
                Intent intent = new Intent(mContext, mClass[position]);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

        // 打开右上角菜单
        ll_menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                new AlertView(null, null, "取消", menuTitles, null, mContext, AlertView.Style.ActionSheet, new com.aihook.alertview.library.OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        if (position == 0) {
                            Intent intent = new Intent(mContext, ConnectSetup.class);
                            startActivity(intent);
                        } else if (position == 1) {
                            unbind();
                        } else if (position == 2) {
                            new UpdateManager(mContext).manualCheckUpdate();
                        } else if (position == 3) {
                            logout();
                        } else if (position == 4 && Build.MODEL.equals(Data.RFID_DEVICE)) {
                            startActivity(new Intent(mContext, RFIDSetting.class));
                        }
                    }
                }).show();
            }
        });

        //RFID
        if (Build.MODEL.equals(Data.RFID_DEVICE)) {
            String[] newMenuTitles = {"RFID设置"};
            int strLen1 = menuTitles.length;// 保存第一个数组长度
            int strLen2 = newMenuTitles.length;
            menuTitles = Arrays.copyOf(menuTitles, strLen1 + strLen2);
            System.arraycopy(newMenuTitles, 0, menuTitles, strLen1, strLen2);
        }
    }

    private void initRFID() {
        PrepareWork();

        try {
            mReaderHelper = ReaderHelper.getDefaultHelper();
            mReaderHelper.setReader(mSerialPort.getInputStream(), mSerialPort.getOutputStream());
            mReader = mReaderHelper.getReader();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }

    // 初始化注销
    private void logout() {
        new AlertView("提示", "确定注销当前用户吗？", "取消", new String[]{"注销"}, null, mContext, AlertView.Style.AlertDialog, new com.aihook.alertview.library.OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
                    Common.deviceLogout(mContext, mActivity); //调用设备退出
                }
            }
        }).show();
    }

    /**
     * 设备解绑
     */
    private void unbind() {
        new AlertView("提示", "确定解除绑定当前设备吗？", "取消", new String[]{"解除绑定"}, null, mContext, AlertView.Style.AlertDialog, new com.aihook.alertview.library.OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
                    Common.deviceUnbind(mContext, mActivity);
                }
            }
        }).show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            logout();
        }
        return false;
    }

    /**
     * 模块上电，打开串口
     */
    private void PrepareWork() {
        if (android.os.Build.VERSION.RELEASE.equals(AndroidVersions.V_4_0_3)) {
            M10_GPIO.R1000_PowerOn(); //模块上电
            try {
                mSerialPort = new SerialPort(new File("dev/ttySAC2"), 115200, 0);
            } catch (SecurityException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        } else if (android.os.Build.VERSION.RELEASE.equals(AndroidVersions.V_5_1_1)) {
            M10A_GPIO.PowerOn(); //模块上电
            try {
                M10A_GPIO._uhf_SwitchSerialPort();
                mSerialPort = new SerialPort(new File("/dev/ttyHSL0"), 115200, 0);
            } catch (SecurityException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        } else {
            Toastor.getInstance().showToast("程序版本有误，请联系技术支持人员！");
        }
    }

    /**
     * 模块下电，关闭串口
     */
    private void EndWork() {
        mSerialPort.close();
        if (android.os.Build.VERSION.RELEASE.equals(AndroidVersions.V_4_0_3)) {
            M10_GPIO.R1000_PowerOFF();
        } else if (android.os.Build.VERSION.RELEASE.equals(AndroidVersions.V_5_1_1)) {
            M10A_GPIO.PowerOff();
        }
//        System.exit(0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EndWork();
    }
}
